import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';
// import 'dart:async';

class RxDartDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("RxDartDemo"),
        elevation: 0.0,
      ),
      body: RxDartDemoHome(),
    );
  }
}

/// rxdart 实例首页
class RxDartDemoHome extends StatefulWidget {
  @override
  _RxDartDemoHomeState createState() => _RxDartDemoHomeState();
}

class _RxDartDemoHomeState extends State<RxDartDemoHome> {

  PublishSubject<String> _textFieldSubject;

  @override
  void initState() {    
    super.initState();

    _textFieldSubject = PublishSubject<String> ();
    _textFieldSubject
      .where((item) => item.length > 9) // 条件筛选
      .map((item) => 'item: $item')
      .debounce((_) => TimerStream(true, Duration(milliseconds: 500))) // 设置延迟, 500 毫秒
      .listen(print);

    // Rx.merge([Stream.fromIterable(['Hello', 'Flutter', 'RxDart'])])
    // .listen(print);

    // RxDart 0.23.x moves away from the Observable class, utilizing Dart 2.6's new extension methods instead.
    // 官方说明 RxDart 0.23.x 脱离了 Observable 类，使用 Dart 2.6's 新扩展

    /*
    Stream.fromIterable(['Hello', 'RxDart'])
      .delay(Duration(seconds: 3))
      .listen(print);
    */

    // PublishSubject<String> _subject = PublishSubject<String>();
    // _subject.listen((data) => print("listen 1 : $data"));
    // _subject.add("Hello ~~~");
    // _subject.listen((data) => print("listen 2 : ${data.toUpperCase()}"));
    // _subject.add("RxDart ~~~");
    // _subject.close();

    // BehaviorSubject<String> _subject = BehaviorSubject<String>();
    // _subject.listen((data) => print("listen 1 : $data"));
    // _subject.add("Hello ~~~");
    // _subject.listen((data) => print("listen 2 : ${data.toUpperCase()}"));
    // _subject.add("RxDart ~~~");
    // _subject.close();

    /*
    ReplaySubject<String> _subject = ReplaySubject<String>(maxSize: 2); // 设置最大接受数据的个数
    _subject.add("Hello ~~~");
    _subject.add("RxDart ~~~");
    _subject.add("Flutter ~~~");

    _subject.listen((data) => print("listen 1 : $data"));
    _subject.listen((data) => print("listen 2 : ${data.toUpperCase()}"));
    _subject.close();
    */

  }

  @override
  void dispose() {
    super.dispose();
    // 关闭监听
    _textFieldSubject.close();
  }

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: Theme.of(context).copyWith(
        primaryColor: Colors.black,
      ), 
      child: TextField(
        onChanged: (value) {
          _textFieldSubject.add('input: $value');
        },
        onSubmitted: (value) {
          _textFieldSubject.add('submit: $value');
        },
        decoration: InputDecoration(
          labelText: "Title",
          filled: true,
        ),
      ),
    );
  }
}